
# 命令下发
# 检测值更新消息类型 {"type":"temp","num":23}
# 阈值上行
# 阈值更新消息类型 {"type":"temp","num":value}
# 触发报警  0x90
# 解除报警  0x91
# 打开窗户  0x80
# 关闭窗户  0x81




from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO
import socket
import threading
import json
# import eventlet

app = Flask(__name__)
# socketio = SocketIO(app)

UDP_IP = "192.168.3.67"  # 你的UDP服务器IP
UDP_PORT = 2333       # 你的UDP服务器端口

temperature = 10
humidity = 15
smoke = 0.3
light = 1000
# UDP客户端
class UDPClient:
    def __init__(self, ip, port):
        self.server_address = (ip, port)
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.receive_thread = threading.Thread(target=self.receive_messages)
        self.receive_thread.daemon = True
        self.receive_thread.start()

    def send_message(self, message):
        self.sock.sendto(message.encode(), self.server_address)

    def receive_messages(self):
        while True:
            data, addr = self.sock.recvfrom(1024)
            message = data.decode()
            try:
                # 尝试解析 JSON 数据
                json_data = json.loads(message)
                # 获取 JSON 中的 type 和 num 值
                message_type = json_data.get('type', '')
                num_value = json_data.get('num', 0)
                # 在这里使用 message_type 和 num_value 进行你的业务逻辑
                print(f'Type: {message_type}, Num: {num_value}')
                if message_type == 'temp':
                    global temperature 
                    temperature = num_value
                if message_type == 'humi':
                    global humidity
                    humidity = num_value
                if message_type == 'smoke':
                    global smoke
                    smoke = num_value
                if message_type == 'light':
                    global light
                    light = num_value
            except json.JSONDecodeError as e:
                print(f'Error decoding JSON: {e}')
            
# 创建UDP客户端实例
udp_client = UDPClient(UDP_IP, UDP_PORT)

@app.route('/')
def index():
    return render_template('index.html', last_message=app.config.get('last_message', ''))
    
@app.route('/change_info', methods=['POST'])
def change_info():
    global temperature
    global humidity
    global smoke
    global light
    print(temperature)
    data = {'temperature': temperature,'humidity':humidity,'smoke':smoke,'light':light}
    return jsonify(data)

@app.route('/send_message', methods=['POST'])
def send_message():
    return render_template('index.html', last_temperature=last_temperature)

# 温度阈值更新
@app.route('/send_tempThreshold', methods=['POST'])
def send_tempThreshold():
    message = request.json.get('message', '')
    message = "{\"type\":\"temp\",\"num\":" + message + '}'
    udp_client.send_message(message)
    return jsonify({'status': 'success'})

# 烟雾阈值更新
@app.route('/send_smokeThreshold', methods=['POST'])
def send_smokeThreshold():
    message = request.json.get('message', '')
    message = "{\"type\":\"smoke\",\"num\":" + message + '}'
    udp_client.send_message(message)
    return jsonify({'status': 'success'})

# 光照强度阈值更新
@app.route('/send_lightThreshold', methods=['POST'])
def send_lightThreshold():
    message = request.json.get('message', '')
    message = "{\"type\":\"light\",\"num\":" + message + '}'
    udp_client.send_message(message)
    return jsonify({'status': 'success'})

# 报警控制命令下发
@app.route('/send_alarm', methods=['POST'])
def send_alarm():
    if not hasattr(send_alarm, "counter"):
        send_alarm.counter = 0  # 初始化静态变量

    # 使用if语句进行判断
    if send_alarm.counter == 0:
        udp_client.send_message("0x90")
        send_alarm.counter = 1
    else:
        udp_client.send_message("0x91")
        send_alarm.counter = 0
    return jsonify({'alarm': send_alarm.counter})

# 窗户控制命令下发
@app.route('/send_window', methods=['POST'])
def send_window():
    if not hasattr(send_window, "counter"):
        send_window.counter = 0  # 初始化静态变量

    # 使用if语句进行判断
    if send_window.counter == 0:
        udp_client.send_message("0x80")
        send_window.counter = 1
    else:
        udp_client.send_message("0x81")
        send_window.counter = 0
    return jsonify({'alarm': send_window.counter})


if __name__ == '__main__':
    app.run(debug=True, port=8888)
    
